package cn.jolyoulu.common.core.utils.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: JolyouLu
 * @Date: 2023/4/9 23:54
 * @Description
 */
public class FileUtils {

    /**
     * 获取一个File对象，目录不存在时会自动创建
     *
     * @param path
     * @return
     */
    public static File get(String path, String fileName) {
        File file = new File(path + File.separator + fileName);
        File parentFile = file.getParentFile();
        if (!parentFile.exists() && !parentFile.isDirectory()) {
            parentFile.mkdirs();
        }
        return file;
    }

    /**
     * 压缩文件/文件夹
     *
     * @param fileToZip 要压缩的文件/文件夹
     * @param fileName  要压缩的文件/文件夹名称
     * @param zipOut    压缩包输出路径
     * @throws IOException
     */
    public static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith(File.separator)) {
                zipOut.putNextEntry(new ZipEntry(fileName));
                zipOut.closeEntry();
            } else {
                zipOut.putNextEntry(new ZipEntry(fileName + File.separator));
                zipOut.closeEntry();
            }
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFile(childFile, fileName + File.separator + childFile.getName(), zipOut);
            }
            return;
        }
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }
        fis.close();
    }

    public static void main(String[] args) throws Exception {
//        FileUtils.get("C:\\Users\\mi\\Downloads\\aaa\\wefwef", "aaa.a");
        FileUtils.zipFile(new File("C:\\Users\\mi\\Downloads\\codeGen\\code\\28202fb0883b4ec29803640a01a4551e"),
                new File("C:\\Users\\mi\\Downloads\\codeGen\\code\\28202fb0883b4ec29803640a01a4551e").getName(),
                new ZipOutputStream(new FileOutputStream("C:\\Users\\mi\\Downloads\\codeGen\\code\\28202fb0883b4ec29803640a01a4551e.zip")));
    }
}
